<template>
    <nav class="pl-6 w-full h-full" :style="{ color: 'var(--theme-breadcrumb-default-text)' }" aria-label="Breadcrumb">
        <transition-group
            name="breadcrumb"
            tag="ol"
            class="flex w-full h-full items-center gap-[1px] text-lg list-none"
        >
            <li class="inline-flex items-center" v-for="(item, index) in levelList" :key="item.path">
                <span v-if="index > 0" class="mx-2">/</span>
                <span
                    v-if="index == levelList.length - 1"
                    class="cursor-default"
                    :style="{ color: 'var(--theme-breadcrumb-active-text)' }"
                    >{{ item.meta.title }}</span
                >
                <span v-else>{{ item.meta.title }}</span>
            </li>
        </transition-group>
    </nav>
</template>
<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import { useRoute, useRouter, type RouteLocationMatched } from 'vue-router'

const levelList = ref<RouteLocationMatched[]>([])

const route = useRoute()
const router = useRouter()
watch(
    () => route.path,
    () => {
        getBreadCrumb()
    },
)
const getBreadCrumb = () => {
    let matched: RouteLocationMatched[] = []
    const pathName = findPathNum(route.path)

    if (pathName > 2) {
        // 构建累积路径数组，如 "/a/b/c" => ["/a", "/a/b", "/a/b/c"]
        const segments = route.path.split('/').filter(Boolean)
        let cumulative = ''
        const cumulativePaths = segments.map((seg) => {
            cumulative += `/${seg}`
            return cumulative
        })

        // 通过 router.getRoutes() 查找对应的路由记录
        const routeMap = router.getRoutes()
        const found = cumulativePaths
            .map((p) => routeMap.find((r) => r.path === p))
            .filter((r): r is RouteLocationMatched => !!r && typeof r.meta?.title === 'string')

        matched = found as unknown as RouteLocationMatched[]
    } else {
        matched = route.matched.filter((item) => item.meta && item.meta.title)
    }

    levelList.value = matched.filter((item) => item.meta && item.meta.title)
}

const findPathNum = (str: string, char: string = '/'): number => {
    let index = str.indexOf(char)
    let num = 0
    while (index !== -1) {
        num++
        index = str.indexOf(char, index + 1)
    }
    return num
}
onMounted(() => {
    // 页面初始调用一次
    getBreadCrumb()
})
</script>
<style lang="scss" scoped>
.breadcrumb-list {
    line-height: 50px;
}
</style>
